package com.prabhakar.taxiclubapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.util.taxiclubapp.GPSChecker;

public class WelcomeActivity extends Activity {

	private static String TAG ="WelcomeActivity";
	private static final String Package_Path ="com.prabhakar.taxiclubapp";
	private static final String TaxiClubActivity_ClassPath = "com.prabhakar.taxiclubapp.TaxiClubActivity";
	private static final String CustomerRegisterActivity_Classpath = "com.prabhakar.taxiclubapp.CustomerRegistrationActivity";
	String asyncResponse = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome_main);
		
	//	GPSChecker checker = new GPSChecker();
		
		Button book_taxi_button = (Button)findViewById(R.id.bookingButton);
		book_taxi_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				TAG = TAG+"setOnClickListener >> ";
				if(isInternetOn()){
					Intent startTaxiBookingIntent = new Intent();
					startTaxiBookingIntent.setComponent(new ComponentName(Package_Path, TaxiClubActivity_ClassPath));
					WelcomeActivity.this.startActivity(startTaxiBookingIntent);
				}
			}
		});
		
		Button cust_registration_btn = (Button)findViewById(R.id.customerRegistration);
		cust_registration_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.v(TAG, "Inside cust_registration_btn onClick mthd >>>");
				if(isInternetOn()){
					Intent doCustRegisterIntent = new Intent();
					doCustRegisterIntent.setComponent(new ComponentName(Package_Path,CustomerRegisterActivity_Classpath));
					WelcomeActivity.this.startActivity(doCustRegisterIntent);
				}
			}
		});
		
		/*******************************************/
		doCheckDeviceType(this);
		doCheckFareUpdate();
		
		/*******************************************/
	
	}	//--OnCreate Ends--

	public void doCheckFareUpdate(){
		if(isInternetOn()){				
			// calling OnLoad of app to fecth Booking prices && set to FareBean..
			if(FareBean.isBeanEmpty()){			// getEconomy_Day_baseFare().equalsIgnoreCase("0")){
				
				new FetchTCFaresAsync().execute();
			}
		}
	}
	
	
	/*
	 * This method does check-  ARE WE CONNECTED TO THE NET
	*/
	public final boolean isInternetOn()
	{
		String title,message="";
		boolean connected = false;
		ConnectivityManager connec = (ConnectivityManager)
	    getSystemService(Context.CONNECTIVITY_SERVICE);

	  if (connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
			  connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ){
		 
		  // MESSAGE TO SCREEN FOR TESTING (IF REQ)
		  title="Internet ENABLED";
		  message ="Internet is  enabled.";
		//  GPSChecker.showAlertDialog(this, title, message);
		  connected = true;
	 
	  }else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
			  ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ){
		  
		  connected =  false;
		  title= Constants.INTERNET_DISABLED_TITLE ;
		  message = Constants.INTERNET_DISABLED_MESSAGE ;
		  GPSChecker.showAlertDialog(this, title, message);
	  }
	  return connected;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.welcome, menu);
		return true;
	}
	
	/*
	 * Check the Device Type - LDPI/MDPI/HDPI etc
	 */
	private void doCheckDeviceType(WelcomeActivity welcomeActivity) {

		int density= getResources().getDisplayMetrics().densityDpi;

		switch(density)
		{
		case DisplayMetrics.DENSITY_LOW:
		   Toast.makeText(this, "LDPI", Toast.LENGTH_SHORT).show();
		    break;
		case DisplayMetrics.DENSITY_MEDIUM:
		     Toast.makeText(this, "MDPI", Toast.LENGTH_SHORT).show();
		    break;
		case DisplayMetrics.DENSITY_HIGH:
		    Toast.makeText(this, "HDPI", Toast.LENGTH_SHORT).show();
		    break;
		case DisplayMetrics.DENSITY_XHIGH:
		     Toast.makeText(this, "XHDPI", Toast.LENGTH_SHORT).show();
		    break;
		}
		
	}

	/*
	 * private Class that runs  the AsynTask to fetch Fare Values..
	 */
	private class FetchTCFaresAsync extends AsyncTask<Void, Void, String>{

		private static final String Tag ="FetchTCFaresAsync";
		String response;
		JSONArray  jsonResponse = null;
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog = new ProgressDialog(WelcomeActivity.this);
			progressDialog.setMessage("Contacting Remote Server for Updated Fares ...");
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		@Override
		protected String doInBackground(Void... params) {

			jsonResponse = new JSONArray();
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair(Constants.PRICING_Param_NAME ,Constants.PricingTabValue_P2P));	

			try {   
				jsonResponse = new JSONParser().makeHttpFareRequest(Constants.TC_FareURL, "POST",param );
				Log.d(" Fare Response", jsonResponse.toString());
				
			}catch (Exception e) {
				e.printStackTrace();
			}
			return jsonResponse.toString();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(null !=result) response = "Fares Received Successfully from Remote Server";
			progressDialog.setMessage(response);
			progressDialog.dismiss();
			Log.v(Tag,"RESPONSE /result  recevd in onPostExecute() >> "+result);
			parseJsonArray_And_SetFareDetails(result);
		}

		private void parseJsonArray_And_SetFareDetails(String response2) {

			String cartype="";
			String timeOfDay = "";
			JSONObject json = null;
			JSONObject innerJson =null;
			String innerJsonString ="";
			try {
				JSONArray  jsonResponse = new JSONArray(response2);
				Log.v(Tag,"RESPONSE /result  recevd in parseJsonArray() >> "+jsonResponse.toString());
				Log.v(Tag,"jsonResponse.length()>> "+jsonResponse.length());

				for(int i=0;i<jsonResponse.length();i++){
					json =	new JSONObject(jsonResponse.optString(i).toString());
					innerJsonString = json.getString(Constants.Data);
					innerJson = new JSONObject(innerJsonString);
					Log.v(Tag,""+i+"th innerJson >> "+innerJson);

					if(innerJson!=null){
						cartype =innerJson.getString(Constants.CARTYPE);
						timeOfDay = innerJson.getString(Constants.Time);

						if(cartype.equalsIgnoreCase(Constants.SEDAN) && timeOfDay.equalsIgnoreCase(Constants.DAY)){
							FareBean.setSedan_Day_ratePerKm(innerJson.getString(Constants.RatePerKm));
							FareBean.setSedan_Day_baseFare(innerJson.getString(Constants.BaseFare));
						}
						if(cartype.equalsIgnoreCase(Constants.SEDAN) && timeOfDay.equalsIgnoreCase(Constants.NIGHT)){
							FareBean.setSedan_Night_baseFare(innerJson.getString(Constants.BaseFare));
							FareBean.setSedan_Night_ratePerKm(innerJson.getString(Constants.RatePerKm));
						}
						if(cartype.equalsIgnoreCase(Constants.ECONOMY) && timeOfDay.equalsIgnoreCase(Constants.DAY)){
							FareBean.setEconomy_Day_baseFare(innerJson.getString(Constants.BaseFare));
							FareBean.setEconomy_Day_ratePerKm(innerJson.getString(Constants.RatePerKm));
						}
						if(cartype.equalsIgnoreCase(Constants.ECONOMY) && timeOfDay.equalsIgnoreCase(Constants.NIGHT)){
							FareBean.setEconomy_Night_baseFare(innerJson.getString(Constants.BaseFare));
							FareBean.setEconomy_Night_ratePerKm(innerJson.getString(Constants.RatePerKm));
						}
					}

				}

				Log.v(Tag,"Sedan_Day fare + rate >> "+FareBean.getSedan_Day_baseFare() + " - "+FareBean.getSedan_Day_ratePerKm());
				Log.v(Tag,"Sedan_Night fare + rate >> "+FareBean.getSedan_Night_baseFare()+" - "+FareBean.getSedan_Night_ratePerKm());
				Log.v(Tag,"Economy_Day fare + rate >> "+FareBean.getEconomy_Day_baseFare() + " - "+FareBean.getEconomy_Day_ratePerKm());
				Log.v(Tag,"Economy_Night fare + rate >> "+FareBean.getEconomy_Night_baseFare()+" - "+FareBean.getEconomy_Night_ratePerKm());

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}


}
